using System.Reflection;
using Microsoft.OpenApi.Models;

namespace SwaggerTest;

public class Program
{
    public static void Main(string[] args)
    {
        // [.net core的Swagger接口文档使用教程（一）：Swashbuckle - 没有星星的夏季 - 博客园](https://www.cnblogs.com/shanfeng1000/p/13476831.html)
        var builder = WebApplication.CreateBuilder(args);

        // Add services to the container.
        builder.Services.AddControllers();
        
        // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
        builder.Services.AddEndpointsApiExplorer();
        builder.Services.AddSwaggerGen(options =>
        {
            options.SwaggerDoc("天气系统", new OpenApiInfo()
            {
                Version = "v0.0.1",
                Title = "swagger测试项目",
                Description = $"接口文档说明",
                Contact = new OpenApiContact()
                {
                    Name = "管理员",
                    Email = "admin@qq.com",
                    Url = null
                }
            });
            
            options.SwaggerDoc("职工系统", new OpenApiInfo()
            {
                Version = "v0.0.1",
                Title = "swagger测试项目",
                Description = $"接口文档说明",
                Contact = new OpenApiContact()
                {
                    Name = "管理员",
                    Email = "admin@qq.com",
                    Url = null
                }
            });
            
            var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            // params ( xml文件地址, 是否包含控制器的注释 )
            options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename), true);
        });

        var app = builder.Build();

        // Configure the HTTP request pipeline.
        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                // Select a definition 下拉框
                options.SwaggerEndpoint("/swagger/职工系统/swagger.json", "职工系统");
                options.SwaggerEndpoint("/swagger/天气系统/swagger.json", "天气系统");
                
                // 请求拦截响应器
                options.UseRequestInterceptor("(req) => { req.headers['X-Custom-Header'] = 'Value'; return req; }");
                
                // 响应拦截响应器
                const int num = 123;
                const string token = "Bearer 123123123213123213";
                const string obj = "{ name: '张三', age: 18 }";
                options.UseResponseInterceptor($"(res) => {{ if( res.url.indexOf('.') == -1 ) {{ console.log('Received response:', res); console.log('num', {num}); console.log('token', '{token}'); console.log('obj', {obj}); }} return res; }}");
            });

            app.UseHttpsRedirection();

            app.UseAuthorization();

            app.MapControllers();

            app.Run();
        }
    }
}